package com.kai.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Properties;

public class FileUtil {

    /**
     * 得到文件上传的路径
     */
    public static String PATH = "E:/upload/";

    static {
        InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream("file.properties");
        Properties properties = new Properties();
        try {
            properties.load(stream);
            PATH = properties.getProperty("path");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //文件下载
    public static ResponseEntity<Object> downloadFile(HttpServletResponse response, String path, String oldName) throws IOException {


        File file = new File(FileUtil.PATH, path);

        if (file.exists()) {
            oldName = URLEncoder.encode(oldName, "UTF-8");
            byte[] bytes = FileUtils.readFileToByteArray(file);

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentDispositionFormData("attachment", oldName);
            return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.CREATED);


        } else {
            PrintWriter out = response.getWriter();
            out.write("文件不存在");
            out.flush();
            out.close();
        }
        return null;
    }

    public static String updateFileName(String name, String suffix) {

        File file = new File(PATH, name);

        if (file.exists()) {
            file.renameTo(new File(PATH, name.replace(suffix, "")));
            return name.replace(suffix, "");
        }
        return null;
    }


    public static void deleteFile(String path) {

        String realPath = PATH + path;
        File file = new File(realPath);
        if (file.exists()) {
            file.delete();
        }
    }


}
